/*
 * @Author: lyx 2858535420@qq.com
 * @Date: 2023-02-28 17:02:11
 * @LastEditors: lyx 2858535420@qq.com
 * @LastEditTime: 2023-04-26 16:51:28
 * @FilePath: /bangand-low-code/src/api/manage.js
 * @Description: 通用通讯管理方法
 */

import Vue from 'vue';
import {
  request
} from '@/utils/request';

export const manager = {

  /**
   * @description: post 访问方式
   * @param {string} url
   * @param {any} params
   * @return {*}
   */
  post(url, params, headers = {}) {
    return request({
      url,
      method: 'post',
      headers,
      data: params
    });
  },

  /**
   * @description:  get 访问方式
   * @param {string} url
   * @param {any} params
   * @return {*}
   */
  get(url, params, headers = {}) {
    return request({
      url,
      method: 'get',
      headers,
      params
    });
  },

  /**
   * put 访问方式
   * 
   * @param {*} url 
   * @param {*} params 
   * @param {*} headers 
   * @returns 
   */
  put(url, params = {}, headers = {}) {
    return request({
      url,
      data: params,
      headers,
      method: 'put'
    });
  },

  /**
   * delete action
   * 
   * @param {*} url 
   * @param {*} params 
   * @param {*} headers 
   * @returns 
   */
  delete(url, params = {}, headers = {}) {
    return request({
      url,
      params,
      headers,
      method: 'delete'
    });
  },

  /**
   * 文件上传
   * 
   * @param {*} url 
   * @param {*} data 
   * @returns 
   */
  upload(url, data = {}) {
    return request({
      url,
      method: 'post',
      data,
      headers: {
        // 文件上传
        'Content-Type': 'multipart/form-data'
      }
    });
  },

  /**
   * 文件下载
   * 
   * @param {*} url 
   * @param {*} params 
   * @returns 
   */
  download(url, params = {}) {
    return request({
      url: url,
      params,
      method: 'get',
      responseType: 'blob'
    });
  },

  /**
   * 文件下载
   * 
   * @param {*} url 
   * @param {*} fileName 
   * @param {*} parameter 
   * @returns 
   */
  downloadFile(url, fileName, parameter) {
    return this.downFile(url, parameter).then((data) => {
      if (!data || data.size === 0) {
        Vue.prototype['$message'].warning('文件下载失败');
        return;
      }

      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(new Blob([data]), fileName);
      } else {
        let url = window.URL.createObjectURL(new Blob([data]));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        // 下载完成移除元素
        document.body.removeChild(link);
        // 释放掉blob对象 
        window.URL.revokeObjectURL(url);
      }
    });
  }
};
